package com.yhb.controller;

import com.yhb.conf.ResultCode;
import com.yhb.controller.vo.SingleValueWrapVo;
import lombok.var;
import me.edzh.spring.bootstrap.annotations.EncryptedRequestBody;
import me.edzh.spring.bootstrap.controller.BaseController;
import me.edzh.spring.bootstrap.model.Response;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/bridge")
public class BridgeController extends BaseController {

    private final static String KEY_PREFIX = "bridge-";

    @Autowired
    private RedisTemplate<String, String> redis;

    @PostMapping("/save")
    public Response<SingleValueWrapVo<String>> saveDataAndGenKey(@EncryptedRequestBody SingleValueWrapVo<String> value) {
        var v = value.getFuckingValue();
        if (TextUtils.isEmpty(v)) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "null value forbidden");
        }

        String key = UUID.randomUUID().toString();
        redis.boundValueOps(KEY_PREFIX + key).set(v, 24, TimeUnit.HOURS);

        return Response.ok(new SingleValueWrapVo<>(key));
    }

    @GetMapping("/get/{key}")
    public Response<SingleValueWrapVo<String>> getDataWithKey(@PathVariable("key")String key) {
        if (!redis.hasKey(KEY_PREFIX + key)) {
            throw new ServiceException(ResultCode.ERROR_REDIS_KEY_NOT_EXIST, "has no value for key");
        }
        var value = redis.boundValueOps(KEY_PREFIX + key).get();
        if (TextUtils.isEmpty(value)) {
            throw new ServiceException(ResultCode.ERROR_REDIS_KEY_NOT_EXIST, "has no value for key");
        }

        redis.delete(KEY_PREFIX + key);

        return Response.ok(new SingleValueWrapVo<>(value));
    }
}
